<template>
  <div class="choice-problem-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button @click="$router.back()" icon="ArrowLeft" class="back-btn">返回</el-button>
        <div class="header-info">
          <h2>{{ problem?.title || '选择题' }}</h2>
          <div class="problem-meta">
            <el-tag type="primary" size="small">选择题</el-tag>
            <el-tag v-if="problem?.difficulty" :type="getDifficultyTagType(problem.difficulty)" size="small">
              {{ getDifficultyText(problem.difficulty) }}
            </el-tag>
            <span v-if="problem?.points" class="points">{{ problem.points }}分</span>
          </div>
        </div>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="submitAnswer" :disabled="!selectedAnswer || parseOptions(problem?.options || '').length === 0" :loading="submitting">
          <el-icon><Upload /></el-icon>
          提交答案
        </el-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div v-if="problem" class="main-content">
      <div class="problem-container">
        <!-- 题目描述 -->
        <div class="problem-description">
          <h3>题目描述</h3>
          <div class="description-content" v-html="formatDescription(problem.description)"></div>
          
          <!-- 输入格式 -->
          <div v-if="problem.input_format" class="input-format-section">
            <h4>输入格式：</h4>
            <pre class="format-content">{{ problem.input_format }}</pre>
          </div>
          
          <!-- 输出格式 -->
          <div v-if="problem.output_format" class="output-format-section">
            <h4>输出格式：</h4>
            <pre class="format-content">{{ problem.output_format }}</pre>
          </div>
        </div>

        <!-- 选项 -->
        <div class="options-section">
          <h3>请选择正确答案：</h3>
          <div v-if="parseOptions(problem.options || '').length > 0" class="options-list">
            <div
              v-for="(option, index) in parseOptions(problem.options || '')"
              :key="index"
              class="option-item"
              :class="{ selected: selectedAnswer === String.fromCharCode(65 + index) }"
              @click="selectedAnswer = String.fromCharCode(65 + index)"
            >
              <div class="option-radio">
                <div class="radio-circle" :class="{ checked: selectedAnswer === String.fromCharCode(65 + index) }"></div>
              </div>
              <div class="option-content">
                <span class="option-label">{{ String.fromCharCode(65 + index) }}.</span>
                <span class="option-text">{{ option }}</span>
              </div>
            </div>
          </div>
          <div v-else class="no-options-error">
            <el-alert
              title="题目选项缺失"
              description="该题目缺少选项数据，请联系管理员修复。"
              type="error"
              :closable="false"
            />
          </div>
        </div>

        <!-- 提交结果 -->
        <div v-if="submitResult" class="submit-result">
          <div class="result-header">
            <h3>提交结果</h3>
          </div>
          <div class="result-content" :class="submitResult.status">
            <div class="result-status">
              <el-icon v-if="submitResult.status === 'AC'"><CircleCheck /></el-icon>
              <el-icon v-else-if="submitResult.status === 'WA'"><CircleClose /></el-icon>
              <el-icon v-else><Warning /></el-icon>
              {{ getResultStatusText(submitResult.status) }}
            </div>
            <div class="result-details">
              <p>您的答案：{{ selectedAnswer }}</p>
              <p v-if="submitResult.correct_answer">正确答案：{{ submitResult.correct_answer }}</p>
              <p>得分：{{ submitResult.score }}/{{ submitResult.max_score }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-else-if="loading" class="loading-container">
      <div v-loading="true" style="height: 200px;"></div>
      <p>加载题目中...</p>
    </div>

    <!-- 错误状态 -->
    <div v-else class="error-container">
      <el-empty description="题目不存在或加载失败" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { CircleCheck, CircleClose, Warning } from '@element-plus/icons-vue'
import { problemsApi } from '@/api/problems'
import type { Problem } from '@/types'

const route = useRoute()
const router = useRouter()

const problem = ref<Problem | null>(null)
const loading = ref(true)
const submitting = ref(false)
const selectedAnswer = ref('')
const submitResult = ref<any>(null)

// 加载题目
const loadProblem = async () => {
  try {
    loading.value = true
    const response = await problemsApi.getProblem(Number(route.params.id))
    problem.value = response
    
    // 检查题目类型
    if (problem.value && problem.value.type !== 'choice') {
      ElMessage.error('此页面仅适用于选择题')
      router.back()
      return
    }
  } catch (error: any) {
    console.error('加载题目失败:', error)
    ElMessage.error('加载题目失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 提交答案
const submitAnswer = async () => {
  if (!selectedAnswer.value) {
    ElMessage.warning('请先选择答案')
    return
  }

  try {
    submitting.value = true
    
    // 直接比较答案
    const isCorrect = selectedAnswer.value === problem.value?.answer
    const score = isCorrect ? (problem.value?.points || 10) : 0
    
    submitResult.value = {
      status: isCorrect ? 'AC' : 'WA',
      score: score,
      max_score: problem.value?.points || 10,
      correct_answer: problem.value?.answer
    }
    
    if (isCorrect) {
      ElMessage.success('回答正确！')
    } else {
      ElMessage.warning('回答错误，请重新尝试')
    }
  } catch (error: any) {
    console.error('提交答案失败:', error)
    ElMessage.error('提交答案失败，请重试')
  } finally {
    submitting.value = false
  }
}

// 解析选项
const parseOptions = (options: string | string[] | null) => {
  if (!options) {
    // 如果没有选项，返回空数组并在界面显示错误信息
    return []
  }
  
  // 如果传入的是数组，直接返回
  if (Array.isArray(options)) {
    return options
  }
  
  // 如果传入的不是字符串，尝试转换
  if (typeof options !== 'string') {
    console.warn('选项数据类型异常:', typeof options, options)
    return []
  }
  
  try {
    const parsed = JSON.parse(options)
    return Array.isArray(parsed) ? parsed : []
  } catch (error) {
    console.error('解析选项失败:', error, '原始数据:', options)
    
    // 尝试其他解析方式
    if (typeof options === 'string') {
      // 如果包含逗号，尝试按逗号分割
      if (options.includes(',') && !options.startsWith('[')) {
        const splitOptions = options.split(',').map(opt => opt.trim()).filter(opt => opt.length > 0)
        if (splitOptions.length > 0) {
          console.log('使用逗号分割解析:', splitOptions)
          return splitOptions
        }
      }
    }
    
    return []
  }
}

// 格式化题目描述
const formatDescription = (description: string) => {
  return description.replace(/\n/g, '<br>')
}

// 获取难度标签类型
const getDifficultyTagType = (difficulty: string) => {
  const typeMap: Record<string, string> = {
    easy: 'success',
    medium: 'warning',
    hard: 'danger'
  }
  return typeMap[difficulty] || 'info'
}

// 获取难度文本
const getDifficultyText = (difficulty: string) => {
  const textMap: Record<string, string> = {
    easy: '简单',
    medium: '中等',
    hard: '困难'
  }
  return textMap[difficulty] || difficulty
}

// 获取结果状态文本
const getResultStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    AC: '答案正确',
    WA: '答案错误',
    CE: '编译错误',
    TLE: '时间超限',
    MLE: '内存超限',
    RE: '运行时错误',
    PE: '格式错误'
  }
  return statusMap[status] || status
}

onMounted(() => {
  loadProblem()
})
</script>

<style scoped lang="scss">
.choice-problem-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);

  .header-left {
    display: flex;
    align-items: center;
    gap: 20px;

    .back-btn {
      background: linear-gradient(45deg, #667eea, #764ba2);
      border: none;
      color: white;
      border-radius: 8px;
      padding: 10px 15px;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
      }
    }

    .header-info {
      h2 {
        margin: 0 0 8px 0;
        color: #2c3e50;
        font-size: 1.8rem;
        font-weight: 600;
      }

      .problem-meta {
        display: flex;
        gap: 10px;
        align-items: center;

        .points {
          font-weight: 600;
          color: #e74c3c;
          background: rgba(231, 76, 60, 0.1);
          padding: 4px 8px;
          border-radius: 4px;
        }
      }
    }
  }

  .header-right {
    .el-button {
      background: linear-gradient(45deg, #667eea, #764ba2);
      border: none;
      border-radius: 8px;
      padding: 12px 24px;
      font-weight: 600;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
      }

      &:disabled {
        background: #ccc;
        transform: none;
        box-shadow: none;
      }
    }
  }
}

.main-content {
  .problem-container {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    border-radius: 12px;
    padding: 30px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);

    .problem-description {
      margin-bottom: 30px;

      h3 {
        color: #2c3e50;
        margin-bottom: 15px;
        font-size: 1.4rem;
        font-weight: 600;
      }

      .description-content {
        color: #34495e;
        line-height: 1.6;
        font-size: 1.1rem;
      }
    }

    .options-section {
      margin-bottom: 30px;

      h3 {
        color: #2c3e50;
        margin-bottom: 20px;
        font-size: 1.3rem;
        font-weight: 600;
      }

      .options-list {
        display: flex;
        flex-direction: column;
        gap: 15px;

        .option-item {
          display: flex;
          align-items: center;
          padding: 15px 20px;
          border: 2px solid #e1e8ed;
          border-radius: 10px;
          cursor: pointer;
          transition: all 0.3s ease;
          background: white;

          &:hover {
            border-color: #667eea;
            box-shadow: 0 2px 10px rgba(102, 126, 234, 0.2);
          }

          &.selected {
            border-color: #667eea;
            background: linear-gradient(135deg, rgba(102, 126, 234, 0.1), rgba(118, 75, 162, 0.1));
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
          }

          .option-radio {
            margin-right: 15px;

            .radio-circle {
              width: 20px;
              height: 20px;
              border: 2px solid #ddd;
              border-radius: 50%;
              position: relative;
              transition: all 0.3s ease;

              &.checked {
                border-color: #667eea;
                background: #667eea;

                &::after {
                  content: '';
                  position: absolute;
                  top: 50%;
                  left: 50%;
                  transform: translate(-50%, -50%);
                  width: 8px;
                  height: 8px;
                  background: white;
                  border-radius: 50%;
                }
              }
            }
          }

          .option-content {
            display: flex;
            align-items: center;
            flex: 1;

            .option-label {
              font-weight: 600;
              color: #667eea;
              margin-right: 10px;
              font-size: 1.1rem;
              min-width: 30px;
            }

            .option-text {
              color: #34495e;
              font-size: 1.1rem;
              line-height: 1.4;
            }
          }
        }
      }
    }

    .no-options-error {
      margin: 20px 0;
    }

    .submit-result {
      margin-top: 30px;
      padding: 20px;
      border-radius: 10px;
      background: #f8f9fa;

      .result-header {
        margin-bottom: 15px;

        h3 {
          color: #2c3e50;
          margin: 0;
          font-size: 1.3rem;
          font-weight: 600;
        }
      }

      .result-content {
        &.AC {
          background: rgba(40, 167, 69, 0.1);
          border: 1px solid rgba(40, 167, 69, 0.3);
        }

        &.WA {
          background: rgba(220, 53, 69, 0.1);
          border: 1px solid rgba(220, 53, 69, 0.3);
        }

        .result-status {
          display: flex;
          align-items: center;
          gap: 10px;
          margin-bottom: 15px;
          font-weight: 600;
          font-size: 1.1rem;

          .el-icon {
            font-size: 1.2rem;
          }
        }

        .result-details {
          p {
            margin: 8px 0;
            color: #34495e;
            font-size: 1rem;
          }
        }
      }
    }
  }
}

/* 输入输出格式样式 */
.input-format-section,
.output-format-section {
  margin: 20px 0;
}

.input-format-section h4,
.output-format-section h4 {
  color: #409eff;
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: 600;
}

.format-content {
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  padding: 15px;
  margin: 0;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-break: break-word;
  color: #495057;
  overflow-x: auto;
}

.loading-container, .error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);

  p {
    margin-top: 20px;
    color: #666;
    font-size: 1.1rem;
  }
}
</style>
